import { onMounted, onUnmounted } from 'vue';

type KeyHandler = (event: KeyboardEvent) => void;
type KeyBinding = {
  key: string;
  handler: KeyHandler;
  ctrl?: boolean;
  shift?: boolean;
  alt?: boolean;
};

export function useKeyboard(key: string | KeyBinding[], handler?: KeyHandler) {
  let bindings: KeyBinding[] = [];

  if (typeof key === 'string' && handler) {
    bindings = [{ key, handler }];
  } else if (Array.isArray(key)) {
    bindings = key;
  }

  const handleKeydown = (event: KeyboardEvent) => {
    for (const binding of bindings) {
      const matchesKey = event.key.toLowerCase() === binding.key.toLowerCase();
      const matchesCtrl = !binding.ctrl || event.ctrlKey;
      const matchesShift = !binding.shift || event.shiftKey;
      const matchesAlt = !binding.alt || event.altKey;

      if (matchesKey && matchesCtrl && matchesShift && matchesAlt) {
        binding.handler(event);
      }
    }
  };

  onMounted(() => {
    window.addEventListener('keydown', handleKeydown);
  });

  onUnmounted(() => {
    window.removeEventListener('keydown', handleKeydown);
  });
}

// 预定义的快捷键配置
export const defaultShortcuts = [
  { 
    key: '/', 
    handler: () => {
      (document.querySelector('.search-input input') as HTMLInputElement)?.focus();
    }
  },
  { 
    key: '?', 
    handler: () => {
      (document.querySelector('.shortcuts-modal') as HTMLElement)?.classList.add('show');
    }
  },
  { 
    key: 'n', 
    handler: () => {
      (document.querySelector('.new-board-button') as HTMLElement)?.click();
    }
  },
  { 
    key: 'b', 
    handler: () => window.location.href = '/'
  },
  { 
    key: 'f', 
    handler: () => {
      (document.querySelector('.filter-button') as HTMLElement)?.click();
    }
  },
  { 
    key: 'x', 
    handler: () => {
      (document.querySelector('.archive-button') as HTMLElement)?.click();
    }
  },
  { 
    key: 'Escape', 
    handler: () => {
      (document.querySelector('.modal-close') as HTMLElement)?.click();
    }
  }
]; 